package com.struct.graph.game2.w2d{
	import Box2D.Collision.Shapes.b2CircleShape;
	import Box2D.Collision.Shapes.b2PolygonShape;
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.b2Body;
	import Box2D.Dynamics.b2BodyDef;
	import Box2D.Dynamics.b2DebugDraw;
	import Box2D.Dynamics.b2FixtureDef;
	import Box2D.Dynamics.b2World;
	
	import flash.display.Sprite;

	public class Battle2d {
		private var s:Sprite;
		private const m_physScale:uint = 30;
		public const m_velocityIterations:int = 10;
		public const m_positionIterations:int = 10;
		public var m_timeStep:Number = 1.0/30.0;
		private var m_world:b2World;
		public function Battle2d(s:Sprite){
			this.s = s;
			// Define the gravity vector
			var gravity:b2Vec2 = new b2Vec2(0.0, 10.0);
			// Allow bodies to sleep
			var doSleep:Boolean = true;
			// Construct a world object
			m_world = new b2World(gravity, doSleep);
			m_world.SetWarmStarting(true);
			// set debug draw
			var dbgDraw:b2DebugDraw = new b2DebugDraw();
			dbgDraw.SetSprite(s);
			dbgDraw.SetDrawScale(30.0);
			dbgDraw.SetFillAlpha(0.3);
			dbgDraw.SetLineThickness(1.0);
			dbgDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
			m_world.SetDebugDraw(dbgDraw);
			// Create border of boxes
			var wall:b2PolygonShape = new b2PolygonShape();
			var wallBd:b2BodyDef = new b2BodyDef();
			var wallB:b2Body;
			wall.SetAsBox(50 / m_physScale, 300/m_physScale);
			// Left
			wallBd.position.Set(10 / m_physScale, 300 / m_physScale);
			wallB = m_world.CreateBody(wallBd);
			wallB.CreateFixture2(wall);
			// Right
			wallBd.position.Set((800 - 10) / m_physScale, 300 / m_physScale);
			wallB = m_world.CreateBody(wallBd);
			wallB.CreateFixture2(wall);
			// Top
			wall.SetAsBox(400/m_physScale, 50/m_physScale);
			wallBd.position.Set(400 / m_physScale, 10 / m_physScale);
			wallB = m_world.CreateBody(wallBd);
			wallB.CreateFixture2(wall);
			// Bottom
			wallBd.position.Set(400 / m_physScale, (600 - 10) / m_physScale);
			wallB = m_world.CreateBody(wallBd);
			wallB.CreateFixture2(wall);
		}
		
		public function addBall2Word():b2Body{
			var cd:b2CircleShape;
			var bd:b2BodyDef;
			var body:b2Body;
			var fd:b2FixtureDef;
			cd = new b2CircleShape(15/m_physScale);
			fd = new b2FixtureDef();
			fd.shape = cd;
			fd.friction = 10;
			fd.restitution = .5;
			fd.density = 1.0;
			fd.filter.groupIndex = -1;
			bd = new b2BodyDef();
			bd.type = b2Body.b2_dynamicBody;
			// Position in world space
			bd.position.Set((Math.random() * 620 + 10)/m_physScale, 350/m_physScale);
			body = m_world.CreateBody(bd);
			body.CreateFixture(fd);
			return body;
		}
		
		public function Update():void {
			// Update physics
			m_world.Step(m_timeStep, m_velocityIterations, m_positionIterations);
			m_world.ClearForces();
			// Render
			m_world.DrawDebugData();
		}
	}
}